package com.bo.sina.weibo.sinakey;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

import org.apache.http.impl.client.DefaultHttpClient;

import com.bo.sina.send.SendGetMessage;
import com.bo.sina.send.WeiboResponse;

public class WeiboKey {
	
	/** 
     * 新浪微博预登录，获取密码加密公钥 
     *  sinaSSOController.preloginCallBack({"retcode":0,"servertime":1371217088,"pcid":"xd-159238391b3686980c659b8c348b18b169e6",
     *  "nonce":"SWL06I",
     *  "pubkey":"EB2A38568661887FA180BDDB5CABD5F21C7BFD59C090CB2D245A87AC253062882729293E5506350508E7F9AA3BB77F4333231490F915
     *  F6D63C55FE2F08A49B353F444AD3993CACC02DB784ABBB8E42A9B1BBFFFB38BE18D78E87A0E41B9B8F73A928EE0CCEE1F6739884B9777E4FE9E88A
     *  1BBE495927AC4A799B3181D6442443","rsakv":"1330428213","exectime":1})
     * @param unameBase64 
     * @return 返回从结果获取的参数的哈希表 
     * @throws IOException 
     */  
    public   HashMap<String, String> preLogin(String unameBase641,DefaultHttpClient client)  
            throws IOException {
    	
        String url = "http://login.sina.com.cn/sso/prelogin.php?" +
        		"entry=weibo&callback=sinaSSOController.preloginCallBack&su=&rsakt=" +
        		"mod&client=ssologin.js(v1.4.5)&_=" + "_=" + new Date().getTime();
        SendGetMessage sgm=new SendGetMessage();
        WeiboResponse temp=sgm.send(url, "GBK");
//        System.out.println(temp);
        return getParaFromResult(temp.getMessage());  
    }  
    
    /**
	 * 计算64位密文
	 * @param account
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
//	private static String encodeAccount(String account) throws UnsupportedEncodingException {
//		String userName = "";
//			userName = Base64.encodeBase64String(URLEncoder.encode(account,"UTF-8").getBytes());
//		//userName = BASE64Encoder.encode(URLEncoder.encode(account,"UTF-8").getBytes());
//		return userName;
//	}

    

    
    /** 
     * 从新浪返回的结果字符串中获得参数 
     *  
     * @param result 
     * @return 
     */  
    private static HashMap<String, String> getParaFromResult(String result) {  
        HashMap<String, String> hm = new HashMap<String, String>();  
        result = result.substring(result.indexOf("{") + 1, result.indexOf("}"));  
        String[] r = result.split(",");  
        String[] temp;  
        for (int i = 0; i < r.length; i++) {  
            temp = r[i].split(":");  
            for (int j = 0; j < 2; j++) {  
                if (temp[j].contains("\""))  
                    temp[j] = temp[j].substring(1, temp[j].length() - 1);  
            }  
            hm.put(temp[0], temp[1]);  
        }  
        return hm;  
    }  
}
